package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client2 {
    private Socket socket;
    public Client2(){
        try {
            System.out.println("正在连接服务器");
          socket=new Socket("localhost",8088);
          //  socket=new Socket("176.125.111.235",8088);

            //socket=new Socket("176.125.111.251",8088);
           // socket=new Socket("176.125.111.237",8189);
            System.out.println("与服务器连接成功");
            System.out.println("型芯不");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    void start(){
        try {
            OutputStream out =socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bw,true);

            InputStream is = null;
            is = socket.getInputStream();//服务端的公告输入流
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);

            Scanner sc=new Scanner(System.in);
            System.out.println("请输入您想发送的消息,按回车发送");

            Thread ne=new Thread(){
                String lineAccept;
                public void run() {
                    while (true) {
                        try {
                            if (!((lineAccept=br.readLine())!=null)) break;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        System.out.println("服务端返回:"+socket.getInetAddress().getHostAddress()+":"+lineAccept);
                    }
                }
            };
            ne.start();
            while (true){
                String line=sc.next();
                if("exit".equals(line))
                    break;
                pw.println(line);
            }
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                System.out.println("over...");
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client2 client=new Client2();
        client.start();
        //BufferedInputStream bis=new BufferedInputStream();
        BufferedOutputStream bos;
        //bos.flush();
    }

}
